// API基础URL
const BASE_API = "http://localhost:9999";

// 分页参数
let currentPage = 1;
const pageSize = 10;
let totalPages = 0;
let totalRecords = 0;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 配置toastr提示框
    toastr.options = {
        "closeButton": true,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "timeOut": "3000"
    };

    // 获取token
    const token = localStorage.getItem('token');
    if (!token) {
        window.location.href = 'login.html';
        return;
    }

    // 初始化加载
    refreshList();

    // 绑定搜索事件
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchByUserId();
        }
    });
});

// 刷新日志列表
function refreshList() {
    const params = {
        page: currentPage,
        pageSize: pageSize
    };

    $.ajax({
        url: `${BASE_API}/operationLog/list`,
        type: 'GET',
        headers: {
            'token': localStorage.getItem('token')
        },
        data: params,
        success: function(result) {
            console.log('Response:', result);
            if (result.code === 200) {
                if (result.data && Array.isArray(result.data.records)) {
                    // 分页数据
                    displayLogs(result.data.records);
                    renderPagination(result.data.total);
                } else if (Array.isArray(result.data)) {
                    // 直接是数组数据
                    displayLogs(result.data);
                    renderPagination(result.data.length);
                } else {
                    toastr.error('数据格式错误');
                }
            } else if (result.code === -2) {
                window.location.href = 'login.html';
            } else {
                toastr.error(result.msg || '获取日志列表失败');
            }
        },
        error: function(xhr, status, error) {
            console.error('Error:', error);
            toastr.error('获取日志列表失败，请检查网络连接');
        }
    });
}

// 根据用户ID搜索
function searchByUserId() {
    const userId = document.getElementById('searchInput').value.trim();
    if (!userId) {
        toastr.warning('请输入用户ID');
        return;
    }
    
    $.ajax({
        url: `${BASE_API}/operationLog/user/${userId}`,
        type: 'GET',
        headers: {
            'token': localStorage.getItem('token')
        },
        success: function(result) {
            console.log('Search Response:', result);
            if (result.code === 200) {
                if (Array.isArray(result.data)) {
                    displayLogs(result.data);
                    renderPagination(result.data.length);
                } else {
                    toastr.error('数据格式错误');
                }
            } else if (result.code === -2) {
                window.location.href = 'login.html';
            } else {
                toastr.error(result.msg || '搜索日志失败');
            }
        },
        error: function(xhr, status, error) {
            console.error('Error:', error);
            toastr.error('搜索日志失败，请检查网络连接');
        }
    });
}

// 显示日志数据
function displayLogs(logs) {
    console.log('Displaying logs:', logs);
    const tbody = document.getElementById('logTableBody');
    tbody.innerHTML = '';
    
    if (!logs || logs.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" class="text-center">暂无数据</td></tr>';
        return;
    }

    logs.forEach(log => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${log.id || '-'}</td>
            <td>${log.username || '-'}</td>
            <td>${log.operation || '-'}</td>
            <td>${log.operationType || '-'}</td>
            <td>${log.ipAddress || '-'}</td>
            <td>${formatDateTime(log.createTime)}</td>
        `;
        tbody.appendChild(tr);
    });
}

// 渲染分页
function renderPagination(total) {
    totalRecords = total;
    totalPages = Math.ceil(total / pageSize);
    
    // 更新页码信息显示
    document.getElementById('pageInfo').textContent = `第 ${currentPage} 页 / 共 ${totalPages} 页`;
    document.getElementById('totalInfo').textContent = `共 ${totalRecords} 条`;
    
    // 更新按钮状态
    document.getElementById('prevPage').disabled = currentPage <= 1;
    document.getElementById('nextPage').disabled = currentPage >= totalPages;
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '-';
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
}

// 上一页
function prevPage() {
    if (currentPage > 1) {
        currentPage--;
        refreshList();
    }
}

// 下一页
function nextPage() {
    if (currentPage < totalPages) {
        currentPage++;
        refreshList();
    }
} 